<?php

namespace App\Http\Controllers\Innerend;


use App\Models\ArticleComment;
use App\Models\Fresh;
use App\Models\FreshComplain;
use App\Models\User;

class FreshComplainController extends BaseController
{
    // 长短文投诉管理

    public function initialize()
    {
        parent::initialize();

        $this->model = 'FreshComplain';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 返回列表数据
    public function _lists()
    {
        $where = $this->listWhere();
        $page  = $this->page;
        $rows  = $this->rows;
        $model = $this->checkModel($this->model);
        if($model === false){
            return $this->error($this->error);
        }

        // 模型 和 查询
        if($where){
            $result = $model->listPage($where, $page, $rows, "id DESC");
        } else{
            $result = $model->isCache(true)->listPage($where, $page, $rows, "id DESC");
        }
        // 用户头像，粉丝数量，关注数量，金币数
        if($result['list']){
            $freshDb = new Fresh();
            $userDb  = new User();
            // 长短文
            $fids   = array_column($result['list'], 'fresh_id');
            $freshs = $freshDb->isCache(true)->getListInIds($fids);
            // 用户
            $uids1 = array_column($result['list'], 'uid');
            $uids2 = array_column($freshs, 'uid');
            $uids  = array_merge($uids1, $uids2);
            $users = $userDb->isCache(true)->getListInIds($uids);
            $types = $this->userType(); // 认证类型
            foreach($result['list'] as $key => $item){
                $_uid   = $item['uid'];
                $_user  = $users[$_uid] ?? [];
                $_fresh = $freshs[$item['fresh_id']] ?? [];
                // 长短文的用户
                $_fresh['user'] = $users[$_fresh['uid']] ?? [];
                if(!empty($_fresh['user'])){
                    // $_fresh['user']['apply_type'] = $types[$_fresh['user']['apply_type']]['name'] ?? '';
                    $_fresh['user']['apply_type'] = $_fresh['user']['is_apply'] == 1 ? ($types[$_fresh['user']['apply_type']]['name'] ?? '') : '';
                    $_fresh['user']['head_img']   = $this->getHeadImg($_fresh['user']['head_img'] ?? '');
                }

                // 整理
                if($_user){
                    // $_user['apply_type'] = $types[$_user['apply_type']]['name'] ?? '';
                    $_user['apply_type'] = $_user['is_apply'] == 1 ? ($types[$_user['apply_type']]['name'] ?? '') : '';
                    $_user['head_img']   = $this->getHeadImg($_user['head_img'] ?? '');
                } else{
                    $_user = (object)[];
                }

                // 整理
                $result['list'][$key]['user']  = $_user;
                $result['list'][$key]['fresh'] = $_fresh;
            }
        }

        return $this->success($result);
    }


    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $trList = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        // 栏目
        $userDb = new User();
        $uids   = array_column($lists, 'uid');
        $cates  = $userDb->isCache(true)->getListInIds($uids);

        // 展示列表表格
        $listHtml = $this->adminList();
        $verifys  = [0 => '待审核', 1 => '审核通过', 2 => '审核不通过'];
        foreach($lists as $key => $item){
            // 数据
            $_id  = $item['id'];
            $_uid = $item['uid'];
            // 栏目
            $_username = $cates[$_uid]['username'] ?? '-';
            $verify    = $verifys[$item['verify']];

            // 操作
            $operate = $listHtml->operate_edit(['id' => $_id], '审核');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id], '你确定要删除该话题吗？');

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($_username);
            $tr .= $listHtml->list_td($item['fresh_id']);
            $tr .= $listHtml->list_td($item['content']);
            $tr .= $listHtml->list_td($item['reply']);
            $tr .= $listHtml->list_td($verify);
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        // 'role' => '角色',
        return ['uid' => '用户', 'fresh_id' => '长短文id', 'content' => '投诉内容', 'reply' => '反馈', 'verify' => '审核状态', 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
    }

    // 表单页面
    protected function formTable()
    {
        $html = '';
        $info = $this->onShow();
        $form = $this->adminForm();
        if(empty($info)){
            return $this->error('投诉记录不存在！');
        }

        // 栏目
        $userDb  = new User();
        $user    = $userDb->isCache(true)->getOneById($info['uid']);
        $freshDb = new Fresh();

        $username = $form->formShow($user['username']);
        $content  = $form->formShow($info['content'] ?? '');
        $reply    = $form->formInput('reply', $info['reply'] ?? '', '审核反馈');
        $verify   = $form->formRadio('verify', $info['verify'] ?? 1, [1 => '审核通过', 2 => '审核不通过']);

        // 长短文信息
        $fresh     = $freshDb->isCache(true)->getOneById($info['fresh_id']);
        $images    = $this->makeFullFile($fresh['images']);
        $f_title   = $form->formShow($fresh['title']);
        $f_content = $form->formShow($fresh['content']);
        $f_image   = '';
        foreach($images as $image){
            $f_image .= $form->formShowImage($image);
        }

        // 页面
        $html .= $form->makeItem('用户', $username);
        if($fresh['title']){
            $html .= $form->makeItem('长短文标题', $f_title);
        }
        $html .= $form->makeItem('长短文内容', $f_content);
        if($images){
            $html .= $form->makeItem('长短文图片', $f_image);
        }
        $html .= $form->makeItem('投诉内容', $content);
        $html .= $form->makeItem('审核', $verify);
        $html .= $form->makeItem('审核反馈', $reply);


        return $html;
    }

    // 列表搜索
    protected function list_search()
    {
        $request  = $this->getData();
        $form     = $this->adminList();
        $keyword  = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $username = $form->formInput('username', $request['username'] ?? '', '用户名');

        $search = ['keyword' => $keyword, ];  // 'username' => $username
        $this->assign('search', $search);

        $searchHide = ['channel'];
        $this->assign('searchHide', []);
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $addUrl     = url('/innerend/'.$this->controller.'/add');
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">添加</a> ';
        $this->assign('top_button', '');
    }

    // 删除（软删除）
    public function del()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }


    // 查找
    public function show()
    {
        $this->throwIf(empty($this->id), '请指定查看记录');

        $where = [['id', '=', $this->id], ['verify', '>=', 0]];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        $info['images'] = $this->makeFullFile($info['images']);
        // 查找用户信息
        if($info['uid']){
            $uid    = $info['uid'];
            $userDb = new User();
            $types  = $this->userType(); // 认证类型
            // $user   = $userDb->isCache(true)->getListInIds([$uid]);
            $user = $userDb->isCache(true)->getOneById($uid);
            if($user){
                // $user               = $user[$uid];
                $user['head_img']   = $this->getHeadImg($user['head_img'] ?? '');
                $user['apply_type'] = $user['is_apply'] == 1 ? ($types[$user['apply_type']]['name'] ?? '') : '';
                // $user['apply_type'] = $types[$user['apply_type']]['name'] ?? '';
            }
            $info['user'] = $user;
        }

        return $this->success($info);
    }

    // 修改长短文
    public function reply()
    {
        $verify = $this->getData('verify', 0, 'intval');
        $reply  = $this->getData('reply', '', 'trim');
        $this->throwIf(empty($this->id), '请填写回复记录的编号!');
        $this->throwIf(empty($reply), '请填写回复的内容!');
        $this->throwIf(empty($verify), '请填写回复的审核状态!');
        $this->throwIf(!in_array($verify, [1, 2]), '请填写正确回复的审核状态!');

        // TODO 审核
        $this->baiduTextCensor($reply);

        // 执行修改
        $comDb = new FreshComplain();
        $id    = $comDb->onVerify($this->id, $verify, $reply);
        $this->throwIf($id === false, $comDb->getError());

        return $this->success($id);
    }

    // 软删除
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表查询
    protected function listWhere()
    {
        $where    = [['verify', '>=', 0]];
        $fresh_id = $this->getData('fresh_id', 0, 'intval');
        $keyword  = $this->getData('keyword', null, 'trim');
        if($keyword){
            $where[] = ['content', 'like', $keyword];
        }
        if($fresh_id){
            $where[] = ['fresh_id', '=', $fresh_id];
        }

        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            // 'id'       => $this->getData("id", 0, 'intval'),
            'uid'      => $this->getData("uid", 0, 'intval'),
            'fresh_id' => $this->getData("fresh_id", 0, 'intval'),
            'content'  => $this->getData("content", null, 'trim'),
            // 'reply'    => $this->getData("reply", null, 'trim'),
            'verify'   => 0,
            // 'ctime'    => $this->getData("ctime", 0, 'intval'),
            // 'mtime'    => $this->getData("mtime", 0, 'intval'),
        ];

        // TODO 审核
        $this->baiduTextCensor($data);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data = [
            'uid'      => $this->getData("uid", 0, 'intval'),
            'fresh_id' => $this->getData("fresh_id", 0, 'intval'),
            'reply'    => $this->getData("reply", null, 'trim'),
            // 'content'  => $this->getData("content", null, 'trim'),
            'verify'   => $this->getData("verify", 0, 'intval'),
        ];

        // TODO 审核
        $this->baiduTextCensor($data);


        return $data;
    }

}


